<template>
  <div class="order-management-container">
    <div class="page-header">
      <h1>订单管理</h1>
      <div class="header-actions">
        <div class="search-area">
          <el-input
            v-model="searchQuery"
            placeholder="输入订单号或用户信息搜索"
            prefix-icon="Search"
            :style="{ width: '300px' }"
            @keyup.enter="handleSearch"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="clearSearch">清空</el-button>
        </div>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="ordersList"
        :default-sort="{ prop: 'id', order: 'descending' }"
      >
        <!-- 添加序号列 -->
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="order_number"
          label="订单号"
          width="240"
          align="center"
        />
        <el-table-column label="用户信息" width="180" align="center">
          <template #default="scope">
            {{ scope.row.user_username || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="订单状态"
          width="120"
          align="center"
        >
          <template #default="scope">
            <el-tag
              v-if="scope.row.status === 'pending'"
              type="info"
              effect="light"
            >
              待支付
            </el-tag>
            <el-tag
              v-else-if="scope.row.status === 'paid'"
              type="success"
              effect="light"
            >
              已支付
            </el-tag>
            <el-tag
              v-else-if="scope.row.status === 'shipped'"
              type="primary"
              effect="light"
            >
              已发货
            </el-tag>
            <el-tag v-else-if="scope.row.status === 'delivered'" type="success">
              已完成
            </el-tag>
            <el-tag
              v-else-if="scope.row.status === 'cancelled'"
              type="danger"
              effect="light"
            >
              已取消
            </el-tag>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="total_price"
          label="订单金额"
          width="120"
          align="center"
        >
          <template #default="scope">
            {{ "¥" + parseFloat(scope.row.total_price).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="order_time"
          label="下单时间"
          width="180"
          align="center"
        >
          <template #default="scope">
            {{ formatDate(scope.row.order_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button size="small" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
            <el-button
              v-if="
                scope.row.status === 'pending' || scope.row.status === 'paid'
              "
              size="small"
              type="primary"
              @click="
                handleUpdateStatus(
                  scope.row,
                  scope.row.status === 'pending' ? 'paid' : 'shipped'
                )
              "
            >
              {{ scope.row.status === "pending" ? "标记已支付" : "标记已发货" }}
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="danger"
              @click="handleCancelOrder(scope.row)"
            >
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        size="small"
        background
        layout="sizes, prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="selectedOrder" class="order-detail">
        <div class="order-info">
          <h3>订单信息</h3>
          <div class="info-row">
            <span class="label">订单号：</span>
            <span class="value">{{ selectedOrder.order_number }}</span>
          </div>
          <div class="info-row">
            <span class="label">订单状态：</span>
            <span class="value">
              <el-tag
                v-if="selectedOrder.status === 'pending'"
                type="info"
                effect="light"
              >
                待支付
              </el-tag>
              <el-tag
                v-else-if="selectedOrder.status === 'paid'"
                type="success"
                effect="light"
              >
                已支付
              </el-tag>
              <el-tag
                v-else-if="selectedOrder.status === 'shipped'"
                type="primary"
                effect="light"
              >
                已发货
              </el-tag>
              <el-tag
                v-else-if="selectedOrder.status === 'delivered'"
                type="success"
              >
                已完成
              </el-tag>
              <el-tag
                v-else-if="selectedOrder.status === 'cancelled'"
                type="danger"
                effect="light"
              >
                已取消
              </el-tag>
            </span>
          </div>
          <div class="info-row">
            <span class="label">下单时间：</span>
            <span class="value">{{
              formatDate(selectedOrder.order_time)
            }}</span>
          </div>
          <div class="info-row">
            <span class="label">订单金额：</span>
            <span class="value total-price"
              >¥{{ parseFloat(selectedOrder.total_price).toFixed(2) }}</span
            >
          </div>
        </div>
        <div class="order-items">
          <h3>商品信息</h3>
          <el-table :data="selectedOrder.items" border style="width: 100%">
            <el-table-column label="商品图片" width="150" align="center">
              <template #default="scope">
                <img
                  v-if="scope.row.product_image"
                  :src="`http://127.0.0.1:8000${scope.row.product_image}`"
                  :alt="scope.row.product_name"
                  style="width: 100px; height: 100px; object-fit: cover"
                />
                <span v-else>无图片</span>
              </template>
            </el-table-column>
            <el-table-column prop="product_name" label="商品名称" width="200" />
            <el-table-column
              prop="product_price"
              label="单价"
              width="100"
              align="right"
            >
              <template #default="scope">
                ¥{{ parseFloat(scope.row.product_price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="quantity"
              label="数量"
              width="80"
              align="center"
            />
            <el-table-column
              prop="subtotal"
              label="小计"
              width="100"
              align="right"
            >
              <template #default="scope">
                ¥{{ parseFloat(scope.row.subtotal).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import axiosInstance from "../../utils/requests";

// 订单列表相关状态
const ordersList = ref([]);
const currentPage = ref(1);
const total = ref(0);
const pageSize = ref(10);
const searchQuery = ref("");
const loading = ref(false);

// 订单详情弹窗相关状态
const detailDialogVisible = ref(false);
const selectedOrder = ref(null);

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return "-";
  return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
};

//获取订单列表
const getOrdersData = async () => {
  try {
    // 设置加载状态为true
    loading.value = true;
    // 构建查询参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
    };

    // 如果有搜索关键词，添加到查询参数中
    if (searchQuery.value.trim()) {
      params.search = searchQuery.value.trim();
    }

    // 调用API获取订单列表
    const response = await axiosInstance.get("/api/order/orders/", {
      params,
      withCredentials: true,
    });

    // 添加调试信息，查看响应数据结构
    console.log("API响应数据:", response.data);

    // 修改数据处理逻辑，兼容不同的响应结构
    // 假设后端可能直接返回订单数组，或者在data字段中返回
    if (Array.isArray(response.data)) {
      ordersList.value = response.data;
      total.value = response.data.length;
    } else if (response.data.orders) {
      ordersList.value = response.data.orders;
      total.value = response.data.total || response.data.orders.length;
    } else if (response.data.results) {
      ordersList.value = response.data.results;
      total.value = response.data.count || 0;
    } else {
      ordersList.value = [];
      total.value = 0;
    }

    // 如果当前页没有数据且不是第一页，则返回上一页
    if (ordersList.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await getOrdersData();
    }
  } catch (error) {
    // 错误处理
    console.error("获取订单列表失败:", error);
    ElMessage.error(`获取订单列表失败：${error.message || "未知错误"}`);

    // 重置订单列表数据
    ordersList.value = [];
    total.value = 0;
  } finally {
    // 设置加载状态为false
    loading.value = false;
  }
};

// 页码变化处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getOrdersData();
};

// 每页条数变化处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置为第一页
  getOrdersData();
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 重置为第一页
  getOrdersData();
};

// 清空搜索
const clearSearch = () => {
  searchQuery.value = "";
  currentPage.value = 1; // 重置为第一页
  getOrdersData();
};

// 查看订单详情
const handleViewDetail = async (order) => {
  try {
    // 获取完整的订单详情，包括订单项
    const response = await axiosInstance.get(`/api/order/orders/${order.id}/`, {
      withCredentials: true,
    });
    selectedOrder.value = response.data;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error("获取订单详情失败:", error);
    ElMessage.error(`获取订单详情失败：${error.message || "未知错误"}`);
  }
};

// 关闭订单详情弹窗
const handleDetailClose = () => {
  detailDialogVisible.value = false;
  selectedOrder.value = null;
};

// 更新订单状态
const handleUpdateStatus = async (order, newStatus) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要将订单 ${order.order_number} 标记为${
        newStatus === "paid" ? "已支付" : "已发货"
      }吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 调用API更新订单状态
    await axiosInstance.post(
      `/api/order/orders/${order.id}/change_status/`,
      {
        status: newStatus,
      },
      {
        withCredentials: true,
      }
    );

    ElMessage.success(
      `订单已成功标记为${newStatus === "paid" ? "已支付" : "已发货"}`
    );
    // 重新加载订单列表
    getOrdersData();
  } catch (error) {
    // 错误处理或用户取消操作
    if (error === "cancel") {
      return;
    }
    console.error("更新订单状态失败:", error);
    ElMessage.error(`更新订单状态失败：${error.message || "未知错误"}`);
  }
};

// 取消订单
const handleCancelOrder = async (order) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要取消订单 ${order.order_number} 吗？`,
      "取消订单",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger",
      }
    );

    // 调用API取消订单
    await axiosInstance.post(
      `/api/order/orders/${order.id}/change_status/`,
      {
        status: "cancelled",
      },
      {
        withCredentials: true,
      }
    );

    ElMessage.success("订单已成功取消");
    // 重新加载订单列表
    getOrdersData();
  } catch (error) {
    // 错误处理或用户取消操作
    if (error === "cancel") {
      return;
    }
    console.error("取消订单失败:", error);
    ElMessage.error(`取消订单失败：${error.message || "未知错误"}`);
  }
};

onMounted(() => {
  getOrdersData();
});
</script>

<style lang="less" scoped>
.order-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeef3;
}

.header-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.search-area {
  display: flex;
  gap: 10px;
}

.table-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

// 确保表格容器与内容正确对齐
::v-deep .el-table {
  width: 100% !important;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
}

::v-deep .el-table__body-wrapper {
  width: 100% !important;
}

::v-deep .el-table th,
::v-deep .el-table td {
  text-align: center !important;
}

// 订单详情弹窗样式
.order-detail {
  padding: 10px 0;
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.value {
  flex: 1;
  color: #303133;
}

.total-price {
  font-weight: bold;
  color: #e6a23c;
}

.order-info,
.user-info {
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

.order-items {
  margin-top: 16px;
}

.order-info h3,
.user-info h3,
.order-items h3 {
  margin-bottom: 16px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}
</style>
